package com.itheima.reggie.listener;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.*;
import java.util.Timer;
import java.util.TimerTask;

@Slf4j
@Component
public class MessageListener implements HttpSessionAttributeListener, HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        log.info("session打印了。。listener起作用了");
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {

        //当前监听的session
        HttpSession session = se.getSession();

        //获取监听到的session是否为验证码
        String key = se.getName();
        Object value = se.getValue();
        log.info("本次向session存放的数据：key:{},value:{}",key,value);

        //判断该数据是否为验证码
        if(key.startsWith("phone_sms")){
            //是验证码 则开始计时五分钟，五分钟后删除该数据

            //计时5分钟
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    //
                    String code = (String) session.getAttribute(key);
                    if (StrUtil.isNotBlank(code)) {
                        session.removeAttribute(key);
                        log.info("session中的验证码：{}失效了", value);
                    }
                }
                },1000*60*5);

        }

    }
}
